<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医院管理系统 - 患者首页</title>
    <!-- 指定站点图标，避免浏览器请求 /favicon.ico 404 -->
    <!-- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='10' fill='%23007bff'/%3E%3Ctext x='50%' y='55%' text-anchor='middle' font-size='36' fill='white' font-family='Arial'%3EH%3C/text%3E%3C/svg%3E"> -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            min-height: 100vh;
            color: white;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 0;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            padding: 2rem;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .stat-card {
            background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
            color: white;
        }
        .stat-card .card-body {
            padding: 2rem;
        }
        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
        }
        .table {
            border-radius: 10px;
            overflow: hidden;
        }
        .btn-action {
            padding: 5px 10px;
            margin: 2px;
            border-radius: 5px;
        }
        .modal-content {
            border-radius: 15px;
        }
        .form-control, .form-select {
            border-radius: 8px;
        }
        .department-card {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            transition: all 0.3s;
            cursor: pointer;
        }
        .department-card:hover {
            border-color: #007bff;
            transform: translateY(-2px);
        }
        .doctor-card {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: all 0.3s;
            cursor: pointer;
        }
        .doctor-card:hover {
            border-color: #007bff;
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.1);
        }
        .time-slot {
            display: inline-block;
            padding: 8px 16px;
            margin: 4px;
            border: 1px solid #007bff;
            border-radius: 20px;
            background: white;
            color: #007bff;
            cursor: pointer;
            transition: all 0.3s;
        }
        .time-slot:hover {
            background: #007bff;
            color: white;
        }
        .time-slot.selected {
            background: #007bff;
            color: white;
        }
        .time-slot.disabled {
            background: #f8f9fa;
            color: #6c757d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="p-3">
                    <h4 class="text-center mb-4">
                        <i class="fas fa-user me-2"></i>患者中心
                    </h4>
                    <nav class="nav flex-column">
                        <a class="nav-link active" href="#" onclick="showDashboard()">
                            <i class="fas fa-tachometer-alt me-2"></i>首页
                        </a>
                        <a class="nav-link" href="#" onclick="showAppointment()">
                            <i class="fas fa-calendar-plus me-2"></i>预约挂号
                        </a>
                        <a class="nav-link" href="#" onclick="showMyReservations()">
                            <i class="fas fa-calendar-check me-2"></i>我的预约
                        </a>
                        <a class="nav-link" href="#" onclick="showMedicalRecords()">
                            <i class="fas fa-file-medical me-2"></i>我的病历
                        </a>
                        <a class="nav-link" href="#" onclick="showHospitalization()">
                            <i class="fas fa-bed me-2"></i>住院办理
                        </a>
                        <a class="nav-link" href="#" onclick="showMyOrders()">
                            <i class="fas fa-receipt me-2"></i>我的订单
                        </a>
                        <a class="nav-link" href="#" onclick="showDrugPurchase()">
                            <i class="fas fa-pills me-2"></i>购买药品
                        </a>
                        <a class="nav-link" href="#" onclick="showProfile()">
                            <i class="fas fa-user me-2"></i>个人信息
                        </a>
                        <hr>
                        <a class="nav-link" href="#" onclick="logout()">
                            <i class="fas fa-sign-out-alt me-2"></i>退出登录
                        </a>
                    </nav>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- 首页 -->
                <div id="dashboard" class="content-section">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-tachometer-alt me-2"></i>患者首页</h2>
                        <span class="text-muted" id="patientName">欢迎回来，患者</span>
                    </div>

                    <!-- 统计卡片 -->
                    <div class="row mb-4">
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar-check fa-2x mb-2"></i>
                                    <div class="stat-number" id="totalReservations">-</div>
                                    <div>总预约数</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar-day fa-2x mb-2"></i>
                                    <div class="stat-number" id="todayReservations">-</div>
                                    <div>今日预约</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-file-medical fa-2x mb-2"></i>
                                    <div class="stat-number" id="totalRecords">-</div>
                                    <div>病历记录</div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="card stat-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-clock fa-2x mb-2"></i>
                                    <div class="stat-number" id="waitingTime">-</div>
                                    <div>等待时间</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 快速预约和最近预约 -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-bolt me-2"></i>快速预约</h5>
                                </div>
                                <div class="card-body">
                                    <p class="text-muted">选择科室快速预约</p>
                                    <div class="d-grid gap-2">
                                        <button class="btn btn-primary" onclick="showAppointment()">
                                            <i class="fas fa-calendar-plus me-2"></i>立即预约
                                        </button>
                                        <button class="btn btn-outline-primary" onclick="showMyReservations()">
                                            <i class="fas fa-calendar-check me-2"></i>查看预约
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="fas fa-history me-2"></i>最近预约</h5>
                                </div>
                                <div class="card-body">
                                    <div class="list-group list-group-flush">
                                        <div class="list-group-item d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="mb-1">内科 - 张医生</h6>
                                                <small class="text-muted">2024-12-16 09:00</small>
                                            </div>
                                            <span class="badge bg-warning">待就诊</span>
                                        </div>
                                        <div class="list-group-item d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="mb-1">外科 - 李医生</h6>
                                                <small class="text-muted">2024-12-15 14:30</small>
                                            </div>
                                            <span class="badge bg-success">已就诊</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 预约挂号 -->
                <div id="appointment" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-plus me-2"></i>预约挂号</h2>
                    </div>

                    <!-- 预约步骤 -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3 text-center">
                                    <div class="step-item">
                                        <div class="step-number active">1</div>
                                        <div class="step-text">选择科室</div>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="step-item">
                                        <div class="step-number">2</div>
                                        <div class="step-text">选择医生</div>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="step-item">
                                        <div class="step-number">3</div>
                                        <div class="step-text">选择时间</div>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="step-item">
                                        <div class="step-number">4</div>
                                        <div class="step-text">确认预约</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 科室选择 -->
                    <div id="step1" class="appointment-step">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-building me-2"></i>选择科室</h5>
                            </div>
                            <div class="card-body">
                                <div class="row" id="departmentsList">
                                    <!-- 动态加载科室 -->
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 医生选择 -->
                    <div id="step2" class="appointment-step" style="display: none;">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-user-md me-2"></i>选择医生</h5>
                            </div>
                            <div class="card-body">
                                <div class="row" id="doctorsList">
                                    <!-- 动态加载医生 -->
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 时间选择 -->
                    <div id="step3" class="appointment-step" style="display: none;">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-clock me-2"></i>选择时间</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">选择日期</label>
                                        <input type="date" class="form-control" id="appointmentDate" min="">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">选择时段</label>
                                        <div id="timeSlots">
                                            <!-- 动态加载时间段 -->
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 确认预约 -->
                    <div id="step4" class="appointment-step" style="display: none;">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-check-circle me-2"></i>确认预约信息</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>预约详情</h6>
                                        <p><strong>科室：</strong><span id="confirmDepartment">-</span></p>
                                        <p><strong>医生：</strong><span id="confirmDoctor">-</span></p>
                                        <p><strong>日期：</strong><span id="confirmDate">-</span></p>
                                        <p><strong>时段：</strong><span id="confirmTime">-</span></p>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="appointmentInfo" class="form-label">预约备注</label>
                                            <textarea class="form-control" id="appointmentInfo" rows="3" placeholder="请描述您的症状或需求"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="d-flex gap-2">
                                    <button class="btn btn-primary" onclick="confirmAppointment()">
                                        <i class="fas fa-check me-2"></i>确认预约
                                    </button>
                                    <button class="btn btn-outline-secondary" onclick="resetAppointment()">
                                        <i class="fas fa-undo me-2"></i>重新选择
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 我的预约 -->
                <div id="myReservations" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-check me-2"></i>我的预约</h2>
                        <div class="d-flex gap-2">
                            <label for="reservationStatus" class="visually-hidden">预约状态</label>
                            <select class="form-select" id="reservationStatus" aria-label="预约状态筛选" style="width: auto;">
                                <option value="">全部状态</option>
                                <option value="0">待就诊</option>
                                <option value="1">已就诊</option>
                                <option value="2">已取消</option>
                            </select>
                            <button class="btn btn-outline-primary" onclick="loadMyReservations()" type="button" aria-label="按所选状态筛选预约">
                                <i class="fas fa-search me-2" aria-hidden="true"></i>筛选
                            </button>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>预约时间</th>
                                            <th>科室</th>
                                            <th>医生</th>
                                            <th>预约号</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="myReservationsTable">
                                        <tr>
                                            <td colspan="6" class="text-center text-muted">暂无预约记录</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 我的病历 -->
                <div id="medicalRecords" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-file-medical me-2"></i>我的病历</h2>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>就诊时间</th>
                                            <th>科室</th>
                                            <th>医生</th>
                                            <th>诊断结果</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="medicalRecordsTable">
                                        <tr>
                                            <td colspan="5" class="text-center text-muted">暂无病历记录</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 住院办理 -->
                <div id="hospitalization" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-bed me-2"></i>住院办理</h2>
                        <button class="btn btn-primary" onclick="showHospitalizationApplication()">
                            <i class="fas fa-plus me-2"></i>申请住院
                        </button>
                    </div>

                    <!-- 住院申请表单 -->
                    <div id="hospitalizationApplication" class="card mb-4" style="display: none;">
                        <div class="card-header">
                            <h5><i class="fas fa-file-medical me-2"></i>住院申请</h5>
                        </div>
                        <div class="card-body">
                            <form id="hospitalizationForm">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="admissionDepartment" class="form-label">申请科室 *</label>
                                        <select class="form-select" id="admissionDepartment" required>
                                            <option value="">请选择科室</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="admissionDoctor" class="form-label">申请医生</label>
                                        <select class="form-select" id="admissionDoctor">
                                            <option value="">请选择医生（可选）</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="wardType" class="form-label">病房类型 *</label>
                                        <select class="form-select" id="wardType" required>
                                            <option value="">请选择病房类型</option>
                                            <option value="单人间">单人间</option>
                                            <option value="双人间">双人间</option>
                                            <option value="三人间">三人间</option>
                                            <option value="四人间">四人间</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="urgencyLevel" class="form-label">紧急程度 *</label>
                                        <select class="form-select" id="urgencyLevel" required>
                                            <option value="1">普通</option>
                                            <option value="2">紧急</option>
                                            <option value="3">危重</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label for="admissionReason" class="form-label">住院原因 *</label>
                                    <textarea class="form-control" id="admissionReason" rows="3" required 
                                              placeholder="请详细描述病情和住院原因"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="preliminaryDiagnosis" class="form-label">初步诊断</label>
                                    <input type="text" class="form-control" id="preliminaryDiagnosis" 
                                           placeholder="如有初步诊断请填写">
                                </div>
                                <div class="mb-3">
                                    <label for="admissionRemark" class="form-label">备注信息</label>
                                    <textarea class="form-control" id="admissionRemark" rows="2" 
                                              placeholder="其他需要说明的信息"></textarea>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-paper-plane me-2"></i>提交申请
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="cancelHospitalizationApplication()">
                                        <i class="fas fa-times me-2"></i>取消
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- 我的住院申请记录 -->
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-list me-2"></i>我的住院申请</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>申请编号</th>
                                            <th>申请时间</th>
                                            <th>科室</th>
                                            <th>病房类型</th>
                                            <th>紧急程度</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="hospitalizationApplicationsTable">
                                        <tr>
                                            <td colspan="7" class="text-center text-muted">暂无住院申请记录</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 购买药品 -->
                <div id="drugPurchase" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-pills me-2"></i>购买药品</h2>
                        <div>
                            <button class="btn btn-outline-primary" onclick="loadDrugData()"><i class="fas fa-sync-alt me-2"></i>刷新</button>
                        </div>
                    </div>

                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-4">
                                    <label class="form-label">药品分类</label>
                                    <select class="form-select" id="drugCategorySelect" onchange="onCategoryChange()">
                                        <option value="">全部分类</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">搜索药品</label>
                                    <input type="text" class="form-control" id="drugSearchInput" placeholder="输入药品名称关键词" oninput="filterDrugList()">
                                </div>
                                <div class="col-md-4 text-end">
                                    <button class="btn btn-success" onclick="submitDrugPurchase()"><i class="fas fa-paper-plane me-2"></i>提交申请</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-7">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0"><i class="fas fa-capsules me-2"></i>药品列表</h5>
                                    <small class="text-muted" id="drugCountText">-</small>
                                </div>
                                <div class="card-body" style="max-height: 420px; overflow:auto;">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>名称</th>
                                                    <th>规格</th>
                                                    <th>单价</th>
                                                    <th>库存</th>
                                                    <th>数量</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody id="drugTableBody">
                                                <tr><td colspan="6" class="text-center text-muted">加载中...</td></tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-5">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0"><i class="fas fa-shopping-cart me-2"></i>购药清单</h5>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="clearCart()"><i class="fas fa-trash"></i> 清空</button>
                                </div>
                                <div class="card-body" style="max-height: 420px; overflow:auto;">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>药品</th>
                                                    <th>数量</th>
                                                    <th>单价</th>
                                                    <th>小计</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody id="cartTableBody">
                                                <tr><td colspan="5" class="text-center text-muted">暂无药品</td></tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="card-footer d-flex justify-content-between align-items-center">
                                    <div class="h5 mb-0">合计：<span class="text-danger" id="cartTotal">0.00</span> 元</div>
                                    <button class="btn btn-success" onclick="submitDrugPurchase()"><i class="fas fa-paper-plane me-2"></i>提交申请</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card mt-3">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-history me-2"></i>我的购药申请</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>申请编号</th>
                                            <th>申请时间</th>
                                            <th>总金额</th>
                                            <th>状态</th>
                                            <th>明细</th>
                                        </tr>
                                    </thead>
                                    <tbody id="myPurchasesBody">
                                        <tr><td colspan="5" class="text-center text-muted">暂无记录</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 我的订单 -->
                <div id="myOrders" class="content-section" style="display:none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-receipt me-2"></i>我的订单</h2>
                        <div class="d-flex gap-2">
                            <select class="form-select" id="myOrderStatusFilter" style="width:auto;">
                                <option value="">全部</option>
                                <option value="0">未支付</option>
                                <option value="1">已支付</option>
                                <option value="2">已退款</option>
                            </select>
                            <button class="btn btn-outline-primary" onclick="loadMyOrders()"><i class="fas fa-sync-alt me-2"></i>刷新</button>
                        </div>
                    </div>
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>订单号</th>
                                            <th>项目</th>
                                            <th>金额</th>
                                            <th>状态</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="myOrdersTableBody">
                                        <tr><td colspan="6" class="text-center text-muted">暂无订单</td></tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 个人信息 -->
                <div id="profile" class="content-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-user me-2"></i>个人信息</h2>
                        <button class="btn btn-outline-primary" onclick="editProfile()">
                            <i class="fas fa-edit me-2"></i>编辑信息
                        </button>
                    </div>

                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-body">
                                    <form id="profileForm">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">患者ID</label>
                                                <input type="text" class="form-control" id="profilePId" readonly>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">姓名</label>
                                                <input type="text" class="form-control" id="profileName" readonly>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">身份证号</label>
                                                <input type="text" class="form-control" id="profileCardId" readonly>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">手机号</label>
                                                <input type="text" class="form-control" id="profilePhone" readonly>
                                            </div>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">注册时间</label>
                                            <input type="text" class="form-control" id="profileCreateTime" readonly>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5>就诊统计</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <small class="text-muted">总预约次数</small>
                                        <div class="h4 text-primary" id="totalAppointments">0</div>
                                    </div>
                                    <div class="mb-3">
                                        <small class="text-muted">已就诊次数</small>
                                        <div class="h4 text-success" id="completedAppointments">0</div>
                                    </div>
                                    <div class="mb-3">
                                        <small class="text-muted">病历记录数</small>
                                        <div class="h4 text-info" id="totalMedicalRecords">0</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/axios.min.js"></script>
    <script>
        // 配置axios
        axios.defaults.baseURL = '';
        
        // 添加请求拦截器
        axios.interceptors.request.use(function (config) {
            const token = localStorage.getItem('token');
            if (token) {
                config.headers.Authorization = token;
            }
            return config;
        });

        // 添加响应拦截器
        axios.interceptors.response.use(
            function (response) {
                return response;
            },
            function (error) {
                if (error.response && error.response.status === 401) {
                    localStorage.removeItem('token');
                    localStorage.removeItem('userInfo');
                    window.location.href = '/login';
                }
                return Promise.reject(error);
            }
        );

        // 预约相关变量
        let selectedDepartment = null;
        let selectedDoctor = null;
        let selectedDate = null;
        let selectedTime = null;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadUserInfo();
            loadDashboardData();
            loadDepartments();
            setMinDate();
            // 直接尝试加载个人信息，初次进入也能显示
            loadProfile();
        });

        // 设置最小日期为今天
        function setMinDate() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('appointmentDate').min = today;
        }

        // 加载用户信息
        function loadUserInfo() {
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
            if (userInfo.uName) {
                document.getElementById('patientName').textContent = `欢迎回来，${userInfo.uName}`;
            }
        }

        // 显示首页
        function showDashboard() {
            hideAllSections();
            document.getElementById('dashboard').style.display = 'block';
            updateActiveNav('dashboard');
            loadDashboardData();
        }

        // 显示预约挂号
        function showAppointment() {
            hideAllSections();
            document.getElementById('appointment').style.display = 'block';
            updateActiveNav('appointment');
            resetAppointment();
        }

        // 显示我的预约
        function showMyReservations() {
            hideAllSections();
            document.getElementById('myReservations').style.display = 'block';
            updateActiveNav('myReservations');
            loadMyReservations();
        }

        // 显示我的病历
        function showMedicalRecords() {
            hideAllSections();
            document.getElementById('medicalRecords').style.display = 'block';
            updateActiveNav('medicalRecords');
            loadMedicalRecords();
        }

        // 显示住院办理
        function showHospitalization() {
            hideAllSections();
            document.getElementById('hospitalization').style.display = 'block';
            updateActiveNav('hospitalization');
            loadHospitalizationApplications();
            loadDepartmentsForAdmission();
        }

        // 显示购买药品
        function showDrugPurchase() {
            hideAllSections();
            document.getElementById('drugPurchase').style.display = 'block';
            updateActiveNav('drugPurchase');
            loadDrugData();
            loadMyPurchases();
        }

        // 我的订单功能
        function showMyOrders(){
            hideAllSections();
            document.getElementById('myOrders').style.display = 'block';
            updateActiveNav('myOrders');
            loadMyOrders();
        }
        async function loadMyOrders(){
            const tbody = document.getElementById('myOrdersTableBody');
            try{
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载中...</td></tr>';
                const userInfo = JSON.parse(localStorage.getItem('userInfo')||'{}');
                const pId = userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid;
                if (!pId){
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">无法获取患者ID</td></tr>';
                    return;
                }
                const res = await axios.get(`/orders/patient/${pId}`);
                if (!(res.data && res.data.code === 200)){
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                let list = res.data.data || [];
                const statusVal = document.getElementById('myOrderStatusFilter')?.value || '';
                if (statusVal !== ''){
                    list = list.filter(o => String(o.payStatus) === String(statusVal));
                }
                if (!list.length){
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无订单</td></tr>';
                    return;
                }
                const badge = s => s===1? 'bg-success' : (s===2? 'bg-secondary' : 'bg-warning');
                const text = s => s===1? '已支付' : (s===2? '已退款' : '未支付');
                tbody.innerHTML = list.map(o => {
                    const time = o.createTime ? new Date(o.createTime).toLocaleString() : '-';
                    const amt = (Number(o.amount)||0).toFixed(2);
                    const canPay = o.payStatus === 0;
                    return `<tr>
                        <td>OD${o.orderId}</td>
                        <td>${o.item}</td>
                        <td>${amt}</td>
                        <td><span class="badge ${badge(o.payStatus)}">${text(o.payStatus)}</span></td>
                        <td>${time}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" ${canPay? '' : 'disabled'} onclick="payOrder(${o.orderId})">支付</button>
                        </td>
                    </tr>`;
                }).join('');
            }catch(e){
                console.error('加载我的订单失败', e);
                tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
            }
        }
        async function payOrder(orderId){
            try{
                const res = await axios.post(`/orders/pay/${orderId}`);
                if (res.data && res.data.code === 200){
                    alert('支付成功');
                    loadMyOrders();
                } else {
                    alert('支付失败：' + (res.data?.msg || '未知错误'));
                }
            }catch(e){
                console.error('支付失败', e);
                alert('支付失败，请稍后重试');
            }
        }

        // 购物车数据
        const drugCart = new Map(); // key: drugId, value: {drugId, name, spec, price, quantity}

        function onCategoryChange(){
            loadDrugList();
        }

        async function loadDrugData(){
            try {
                const [catRes] = await Promise.all([
                    axios.get('/drug/category/list')
                ]);
                // 分类
                if (catRes.data && catRes.data.code === 200) {
                    const sel = document.getElementById('drugCategorySelect');
                    const cats = catRes.data.data || [];
                    sel.innerHTML = '<option value="">全部分类</option>' + cats.map(c => `<option value="${c.cId}">${c.cName}</option>`).join('');
                }
                await loadDrugList();
            } catch (e) {
                console.error('加载药品数据失败', e);
            }
        }

        async function loadDrugList(){
            try {
                const cId = document.getElementById('drugCategorySelect')?.value || '';
                const url = cId ? `/drug/list?cId=${cId}` : '/drug/list';
                const res = await axios.get(url);
                const tbody = document.getElementById('drugTableBody');
                if (!(res.data && res.data.code === 200)) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const drugs = res.data.data || [];
                document.getElementById('drugCountText').textContent = `共 ${drugs.length} 种药品`;
                const kw = (document.getElementById('drugSearchInput')?.value || '').trim().toLowerCase();
                const filtered = kw ? drugs.filter(d => { const nm = (d.dName||d.dname||d.name||'')+''; return nm.toLowerCase().includes(kw); }) : drugs;
                if (!filtered.length) {
                    tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无药品</td></tr>';
                    return;
                }
                tbody.innerHTML = filtered.map(d => {
                    const price = (d.price != null) ? Number(d.price).toFixed(2) : '0.00';
                    const stock = d.stock != null ? d.stock : 0;
                    return `
                        <tr>
                            <td>${d.dName || d.dname || d.name || ''}</td>
                            <td>${d.spec || ''}</td>
                            <td>${price}</td>
                            <td>${stock}</td>
                            <td style="width:120px">
                                <input type="number" min="1" max="${stock}" value="1" class="form-control form-control-sm" id="qty_${d.drugId}">
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="addToCart(${d.drugId}, '${(d.dName||'').replace(/'/g,"\'")}', '${(d.spec||'').replace(/'/g,"\'")}', ${Number(d.price||0)})">加入</button>
                            </td>
                        </tr>`;
                }).join('');
            } catch (e) {
                console.error('加载药品列表失败', e);
                document.getElementById('drugTableBody').innerHTML = '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        function filterDrugList(){
            loadDrugList();
        }

        function addToCart(drugId, name, spec, price){
            const qtyInput = document.getElementById(`qty_${drugId}`);
            let qty = qtyInput ? parseInt(qtyInput.value,10) : 1;
            if (!qty || qty < 1) qty = 1;
            const exist = drugCart.get(drugId) || { drugId, name, spec, price: Number(price)||0, quantity: 0 };
            exist.quantity += qty;
            drugCart.set(drugId, exist);
            renderCart();
        }

        function clearCart(){
            drugCart.clear();
            renderCart();
        }

        function removeFromCart(drugId){
            drugCart.delete(drugId);
            renderCart();
        }

        function changeCartQty(drugId, qty){
            qty = parseInt(qty,10);
            if (!qty || qty < 1) qty = 1;
            const item = drugCart.get(drugId);
            if (item){ item.quantity = qty; drugCart.set(drugId, item); }
            renderCart();
        }

        function renderCart(){
            const tbody = document.getElementById('cartTableBody');
            if (drugCart.size === 0){
                tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无药品</td></tr>';
                document.getElementById('cartTotal').textContent = '0.00';
                return;
            }
            let total = 0;
            tbody.innerHTML = Array.from(drugCart.values()).map(it => {
                const amount = (Number(it.price)||0) * (Number(it.quantity)||0);
                total += amount;
                return `
                    <tr>
                        <td>${it.name}</td>
                        <td style="width:100px"><input type="number" min="1" value="${it.quantity}" class="form-control form-control-sm" onchange="changeCartQty(${it.drugId}, this.value)"></td>
                        <td>${(Number(it.price)||0).toFixed(2)}</td>
                        <td>${amount.toFixed(2)}</td>
                        <td><button class="btn btn-sm btn-outline-danger" onclick="removeFromCart(${it.drugId})">删除</button></td>
                    </tr>`;
            }).join('');
            document.getElementById('cartTotal').textContent = total.toFixed(2);
        }

        async function submitDrugPurchase(){
            try {
                if (drugCart.size === 0){ alert('请先添加药品'); return; }
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const pId = userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid;
                if (!pId){ alert('未找到患者ID'); return; }
                const items = Array.from(drugCart.values()).map(it => ({ drugId: it.drugId, quantity: it.quantity }));
                const formData = {
                            // 实体字段（后端识别）
                            pId: userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid,
                            items: Array.from(drugCart.values()).map(it => ({ drugId: it.drugId, quantity: it.quantity })),
                            // 兼容别名（部分后端实现/拦截器可能读取这些别名）
                            pid: userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid,
                        };
                const res = await axios.post('/purchase/create', formData);
                if (res.data && res.data.code === 200){
                    alert('提交成功，等待审批');
                    clearCart();
                    loadMyPurchases();
                } else {
                    alert('提交失败：' + (res.data?.msg || '未知错误'));
                }
            } catch (e) {
                console.error('提交购药申请失败', e);
                alert('提交失败，请稍后重试');
            }
        }

        async function loadMyPurchases(){
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const pId = userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid;
                if (!pId){
                    document.getElementById('myPurchasesBody').innerHTML = '<tr><td colspan="5" class="text-center text-muted">无法获取患者ID</td></tr>';
                    return;
                }
                const res = await axios.get(`/purchase/patient/${pId}`);
                const tbody = document.getElementById('myPurchasesBody');
                if (!(res.data && res.data.code === 200)){
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const list = res.data.data || [];
                if (!list.length){
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无记录</td></tr>';
                    return;
                }
                const statusText = s => (s===0?'待审批':(s===1?'已通过':'已拒绝'));
                const badge = s => (s===0?'bg-warning':(s===1?'bg-success':'bg-danger'));
                tbody.innerHTML = list.map(x => {
                    const num = x.purchaseId;
                    const time = x.applyTime ? new Date(x.applyTime).toLocaleString() : '-';
                    const total = (Number(x.totalAmount)||0).toFixed(2);
                    const items = Array.isArray(x.items)? x.items.map(it => `${it.drugName}x${it.quantity}`).join('，') : '';
                    return `<tr>
                        <td>PU${num}</td>
                        <td>${time}</td>
                        <td>${total}</td>
                        <td><span class="badge ${badge(x.status)}">${statusText(x.status)}</span></td>
                        <td title="${items}"><button class="btn btn-sm btn-outline-primary" onclick="alert('${items.replace(/'/g,"\'")}')">查看</button></td>
                    </tr>`;
                }).join('');
            } catch (e) {
                console.error('加载购药记录失败', e);
                document.getElementById('myPurchasesBody').innerHTML = '<tr><td colspan="5" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        // 显示个人信息
        function showProfile() {
            hideAllSections();
            document.getElementById('profile').style.display = 'block';
            updateActiveNav('profile');
            loadProfile();
        }

        // 隐藏所有内容区域
        function hideAllSections() {
            const sections = document.querySelectorAll('.content-section');
            sections.forEach(section => {
                section.style.display = 'none';
            });
        }

        // 更新活跃导航
        function updateActiveNav(activeId) {
            const navLinks = document.querySelectorAll('.nav-link');
            navLinks.forEach(link => {
                link.classList.remove('active');
            });
        }

        // 加载首页数据
        async function loadDashboardData() {
            try {
                // 模拟数据
                document.getElementById('totalReservations').textContent = '12';
                document.getElementById('todayReservations').textContent = '1';
                document.getElementById('totalRecords').textContent = '8';
                document.getElementById('waitingTime').textContent = '15分钟';
            } catch (error) {
                console.error('加载首页数据失败:', error);
            }
        }

        // 加载科室列表
        async function loadDepartments() {
            try {
                const response = await axios.get('/department/query');
                if (response.data.code === 200) {
                    const departments = response.data.data;
                    const container = document.getElementById('departmentsList');
                    container.innerHTML = '';
                    
                    departments.forEach(dept => {
                        const card = `
                            <div class="col-md-6 col-lg-4">
                                <div class="department-card" onclick="selectDepartment(${dept.depId}, '${dept.depName}')">
                                    <h6><i class="fas fa-building me-2"></i>${dept.depName}</h6>
                                    <p class="text-muted small">${dept.depInfo}</p>
                                    <small class="text-muted"><i class="fas fa-phone me-1"></i>${dept.depPhone}</small>
                                </div>
                            </div>
                        `;
                        container.innerHTML += card;
                    });
                }
            } catch (error) {
                console.error('加载科室列表失败:', error);
            }
        }

        // 选择科室
        function selectDepartment(depId, depName) {
            selectedDepartment = { id: depId, name: depName };
            
            // 更新步骤显示
            updateStep(2);
            
            // 加载医生列表
            loadDoctors(depId);
        }

        // 加载医生列表
        async function loadDoctors(depId) {
            // 确保有承载列表的容器
            const ensureContainer = () => {
                let el = document.getElementById('doctorsList');
                if (!el) {
                    const step = document.getElementById('step2');
                    if (step) {
                        // 如果页面里没有容器，动态补一个
                        const wrap = document.createElement('div');
                        wrap.className = 'row';
                        wrap.id = 'doctorsList';
                        step.appendChild(wrap);
                        el = wrap;
                    }
                }
                return el;
            };
            const container = ensureContainer();
            if (container) {
                container.innerHTML = '<div class="text-muted">正在加载医生列表…</div>';
            }
            try {
                let response = null;
                // 1) 首选符合后端的 REST 风格路径
                try {
                    response = await axios.get(`/doctor/query/${depId}`);
                } catch (e) {
                    // ignore
                }
                // 2) 若结构异常或数据为空，回退到获取全部医生再前端过滤
                let doctors = [];
                if (response && response.data && response.data.code === 200 && Array.isArray(response.data.data) && response.data.data.length) {
                    doctors = response.data.data;
                } else {
                    // 获取全部医生
                    let allResp = null;
                    try { allResp = await axios.get('/doctor/query'); } catch (e) { /* ignore */ }
                    const allDoctors = (allResp && allResp.data && allResp.data.code === 200 ? (allResp.data.data || []) : []);
                    // 优先按 depId 过滤，其次按 depName 过滤
                    const byDepId = allDoctors.filter(d => (d.depId || d.depid) == depId);
                    if (byDepId.length) {
                        doctors = byDepId;
                    } else if (selectedDepartment && selectedDepartment.name) {
                        const byDepName = allDoctors.filter(d => (d.depName || d.depname) === selectedDepartment.name);
                        doctors = byDepName;
                    } else {
                        doctors = [];
                    }
                }
                console.log('loadDoctors depId =', depId, 'got doctors =', doctors);
                if (!container) return;
                    container.innerHTML = '';
                if (!doctors.length) {
                    container.innerHTML = '<div class="text-muted">该科室暂无可展示的医生</div>';
                    return;
                }
                    doctors.forEach(doctor => {
                    const dId = doctor.dId || doctor.did || doctor.id;
                    const dName = doctor.dName || doctor.dname || doctor.name || '医生';
                    const dTitle = doctor.dTitle || doctor.dtitle || doctor.title || '';
                    const dMajor = doctor.dMajor || doctor.dmajor || '';
                    const dInfo = doctor.dInfo || doctor.dinfo || '';
                        const card = `
                            <div class="col-md-6 col-lg-4">
                                <div class="doctor-card" onclick="selectDoctor(${dId}, '${dName}', '${dTitle}')">
                                    <h6><i class="fas fa-user-md me-2"></i>${dName}</h6>
                                    <p class="text-muted small">${dTitle} ${dMajor ? ' - ' + dMajor : ''}</p>
                                    <small class="text-muted">${dInfo}</small>
                                </div>
                            </div>
                        `;
                        container.innerHTML += card;
                    });
            } catch (error) {
                console.error('加载医生列表失败:', error);
                const container2 = document.getElementById('doctorsList') || document.getElementById('step2');
                if (container2) {
                    container2.innerHTML = '<div class="text-danger">加载医生失败，请稍后重试</div>';
                }
            }
        }

        // 选择医生
        function selectDoctor(dId, dName, dTitle) {
            selectedDoctor = { id: dId, name: dName, title: dTitle };
            
            // 更新步骤显示
            updateStep(3);
            
            // 初始化时间段区域提示，等待选择日期
            initTimeSlotsPlaceholder();
            
            // 同时加载该医生可预约的具体排班，帮助患者快速选择
            loadDoctorSchedules(dId);
            
            // 监听日期变更，根据所选日期动态加载可用时段
            const dateInput = document.getElementById('appointmentDate');
            if (dateInput) {
                dateInput.onchange = () => populateTimesForDate(selectedDoctor.id, dateInput.value);
            }
        }

        // 初始化时间段容器为提示占位
        function initTimeSlotsPlaceholder() {
            const container = document.getElementById('timeSlots');
            if (container) {
                container.innerHTML = '<div class="text-muted">请选择日期后显示可预约时段</div>';
            }
        }

        // 将后端返回的各种日期形态统一为 yyyy-MM-dd
        function normalizeYMD(val) {
            if (!val) return '';
            try {
                if (typeof val === 'string') {
                    let s = val.split('T')[0].trim();
                    s = s.replace(/\./g, '-').replace(/\//g, '-');
                    const parts = s.split('-').filter(Boolean);
                    if (parts.length === 3) {
                        const y = parts[0];
                        const m = parts[1].padStart(2, '0');
                        const d = parts[2].padStart(2, '0');
                        return `${y}-${m}-${d}`;
                    }
                    // 兜底：Date 解析
                    const d2 = new Date(val);
                    if (!isNaN(d2)) return d2.toISOString().split('T')[0];
                    return '';
                }
                if (val instanceof Date) {
                    if (!isNaN(val)) return val.toISOString().split('T')[0];
                    return '';
                }
                // 其它对象尝试 new Date
                const d3 = new Date(val);
                if (!isNaN(d3)) return d3.toISOString().split('T')[0];
                return '';
            } catch { return ''; }
        }

        // 根据医生与日期加载真实可预约时段
        async function populateTimesForDate(dId, dateStr) {
            const container = document.getElementById('timeSlots');
            if (!container || !dId || !dateStr) return;
            container.innerHTML = '<div class="text-muted">正在加载可预约时段…</div>';
            try {
                let resp = await axios.get(`/schedule/queryWithDoctorInfo/${dId}`);
                if (!resp || resp.data.code !== 200) {
                    resp = await axios.get(`/schedule/query/${dId}`);
                }
                let all = (resp && resp.data && resp.data.code === 200 ? (resp.data.data || []) : []);
                const normalizedSelected = normalizeYMD(dateStr);
                let sameDaySchedules = all.filter(s => (s.remain || 0) > 0 && normalizeYMD(s.date) === normalizedSelected);
                // 兜底：若按医生接口为空，再从全量接口中过滤该医生当日
                if (!sameDaySchedules.length) {
                    try {
                        const allResp = await axios.get('/schedule/query');
                        if (allResp && allResp.data && allResp.data.code === 200) {
                            const allList = allResp.data.data || [];
                            sameDaySchedules = allList.filter(s =>
                                (s.remain || 0) > 0 &&
                                (s.dId === dId || s.did === dId) &&
                                normalizeYMD(s.date) === normalizedSelected
                            );
                        }
                    } catch (e) { /* ignore */ }
                }
            container.innerHTML = '';
                if (!sameDaySchedules.length) {
                    container.innerHTML = '<div class="text-muted">该日期暂无可预约时段，请更换日期</div>';
                    selectedTime = null;
                    return;
                }
                // 渲染每个具体时段按钮（例如 09:30-10:00）
                sameDaySchedules.forEach(s => {
                    const btn = document.createElement('button');
                    btn.className = 'btn btn-outline-primary me-2 mb-2';
                    btn.textContent = s.time || '';
                    btn.onclick = () => {
                        selectedTime = s.time || '';
                        // 激活样式
                        Array.from(container.querySelectorAll('button')).forEach(b => b.classList.remove('active'));
                        btn.classList.add('active');
                        // 更新确认信息 & 校验可用性
                        updateConfirmInfo();
                        checkScheduleAvailability();
                    };
                    container.appendChild(btn);
                });
            } catch (e) {
                console.error('按日期加载可预约时段失败:', e);
                container.innerHTML = '<div class="text-danger">加载失败，请重试</div>';
            }
        }

        // 在第2步下方显示：该医生未来可预约的日期/时段
        async function loadDoctorSchedules(dId) {
            const step = document.getElementById('step2');
            if (!step) return;
            // 容器
            let hint = document.getElementById('doctorScheduleHint');
            if (!hint) {
                hint = document.createElement('div');
                hint.id = 'doctorScheduleHint';
                hint.className = 'mt-3 text-muted';
                step.appendChild(hint);
            }
            hint.textContent = '可预约日期/时段（点击即可选择）：';
            let list = document.getElementById('doctorScheduleList');
            if (!list) {
                list = document.createElement('div');
                list.id = 'doctorScheduleList';
                list.className = 'mt-2';
                step.appendChild(list);
            }
            list.innerHTML = '<div class="text-muted">加载中…</div>';
            try {
                let resp = await axios.get(`/schedule/queryWithDoctorInfo/${dId}`);
                if (!resp || resp.data.code !== 200) {
                    resp = await axios.get(`/schedule/query/${dId}`);
                }
                let all = (resp && resp.data && resp.data.code === 200 ? (resp.data.data || []) : []);
                // 兜底：必要时从全量接口中过滤该医生
                if (!all.length) {
                    try {
                        const allResp = await axios.get('/schedule/query');
                        if (allResp && allResp.data && allResp.data.code === 200) {
                            const allList = allResp.data.data || [];
                            all = allList.filter(s => (s.dId === dId || s.did === dId));
                        }
                    } catch (e) { /* ignore */ }
                }
                // 仅保留可预约且日期在今天之后的
                const todayStr = normalizeYMD(new Date());
                const schedules = all.filter(s => (s.remain || 0) > 0 && normalizeYMD(s.date) >= todayStr);
                if (!schedules.length) {
                    list.innerHTML = '<div class="text-muted">暂未查询到可预约的排班，请更换日期或医生</div>';
                    return;
                }
                // 分组：date -> times
                const map = new Map();
                schedules.forEach(s => {
                    const d = normalizeYMD(s.date);
                    if (!d) return;
                    if (!map.has(d)) map.set(d, []);
                    map.get(d).push(s.time || '');
                });
                // 渲染
                list.innerHTML = '';
                map.forEach((times, date) => {
                    const row = document.createElement('div');
                    row.className = 'mb-2';
                    const title = document.createElement('div');
                    title.className = 'fw-bold';
                    title.textContent = date;
                    row.appendChild(title);
                    const wrap = document.createElement('div');
                    times = [...new Set(times.filter(Boolean))];
                    times.forEach(t => {
                        const btn = document.createElement('button');
                        btn.className = 'btn btn-sm btn-outline-primary me-2 mt-1';
                        btn.textContent = t;
                        btn.onclick = () => {
            const dateInput = document.getElementById('appointmentDate');
                            if (dateInput) dateInput.value = date;
                            selectedTime = t;
                            populateTimesForDate(dId, date);
                            Array.from(list.querySelectorAll('button')).forEach(b => b.classList.remove('active'));
                            btn.classList.add('active');
                            updateConfirmInfo();
                        };
                        wrap.appendChild(btn);
                    });
                    row.appendChild(wrap);
                    list.appendChild(row);
                });
            } catch (e) {
                console.error('加载医生可预约排班失败:', e);
                list.innerHTML = '<div class="text-danger">加载失败，请重试</div>';
            }
        }

        // 加载时间段（改为占位，由 populateTimesForDate 动态渲染）
        function loadTimeSlots() {
            initTimeSlotsPlaceholder();
        }

        // 检查排班可用性
        async function checkScheduleAvailability() {
            const dateRaw = document.getElementById('appointmentDate').value;
            const date = normalizeYMD(dateRaw);
            if (!date || !selectedTime) return;
            
            try {
                const dIdNum = Number(selectedDoctor.id);
                const response = await axios.get('/schedule/isFull', {
                    params: {
                        dId: dIdNum,
                        did: dIdNum,
                        date: date,
                        time: selectedTime
                    }
                });
                
                if (response.data.code === 200) {
                    updateStep(4);
                    updateConfirmInfo();
                } else {
                    alert('该时段已满或医生无排班，请选择其他时间');
                }
            } catch (error) {
                console.error('检查排班失败 params =', { dId: selectedDoctor?.id, date, time: selectedTime }, 'error =', error);
                alert('检查排班失败，请重试');
            }
        }

        // 更新确认信息
        function updateConfirmInfo() {
            document.getElementById('confirmDepartment').textContent = selectedDepartment.name;
            document.getElementById('confirmDoctor').textContent = `${selectedDoctor.name} (${selectedDoctor.title})`;
            document.getElementById('confirmDate').textContent = document.getElementById('appointmentDate').value;
            document.getElementById('confirmTime').textContent = selectedTime;
        }

        // 更新步骤显示
        function updateStep(step) {
            // 隐藏所有步骤容器
            try {
                document.querySelectorAll('.appointment-step').forEach(s => {
                    s.style.display = 'none';
                });
            } catch (e) {
                // ignore
            }
            // 显示当前步骤
            const current = document.getElementById(`step${step}`);
            if (current) current.style.display = 'block';
            
            // 安全更新顶部步骤指示器（如果存在）
            try {
                const indicators = document.querySelectorAll('.step-number');
                if (indicators && indicators.length) {
                    indicators.forEach((el, idx) => {
                        if (idx < step) el.classList.add('active'); else el.classList.remove('active');
                    });
                }
            } catch (e) {
                // ignore
            }
        }

        // 确认预约
        async function confirmAppointment() {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const pId = userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid;
                
                if (!pId) {
                    alert('未找到患者ID，无法提交预约');
                    return;
                }
                if (!selectedDoctor || !selectedDepartment) {
                    alert('请先选择医生与科室');
                    return;
                }
                if (!document.getElementById('appointmentDate').value || !selectedTime) {
                    alert('请先选择日期与时段');
                    return;
                }
                
                const dateStr = normalizeYMD(document.getElementById('appointmentDate').value);
                const dIdNum = Number(selectedDoctor.id);
                const pIdNum = Number(pId);
                const depIdNum = Number(selectedDepartment.id);
                const payload = {
                    // 后端常用字段
                    pId: pIdNum,
                    dId: dIdNum,
                    depId: depIdNum,
                    date: dateStr,
                    time: selectedTime,
                    info: document.getElementById('appointmentInfo').value,
                    // 兼容部分接口需要的小写别名
                    pid: pIdNum,
                    did: dIdNum
                };
                
                const response = await axios.post('/reservation/action', payload);
                
                if (response.data.code === 200) {
                    alert('预约成功！');
                    resetAppointment();
                    showDashboard();
                } else {
                    console.error('预约失败 payload =', payload, 'resp =', response.data);
                    alert('预约失败：' + (response.data.msg || '未知错误'));
                }
            } catch (error) {
                console.error('预约失败 payload error =', error);
                alert('预约失败，请检查网络连接');
            }
        }

        // 重置预约
        function resetAppointment() {
            selectedDepartment = null;
            selectedDoctor = null;
            selectedDate = null;
            selectedTime = null;
            
            document.getElementById('appointmentDate').value = '';
            document.getElementById('appointmentInfo').value = '';
            document.querySelectorAll('.time-slot').forEach(slot => {
                slot.classList.remove('selected');
            });
            
            updateStep(1);
        }

        // 加载我的预约
        async function loadMyReservations() {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const pId = userInfo.pId || userInfo.id || userInfo.uid;
                
                if (!pId) {
                    document.getElementById('myReservationsTable').innerHTML = 
                        '<tr><td colspan="6" class="text-center text-muted">无法加载：缺少患者ID</td></tr>';
                    return;
                }
                
                // 并行获取预约列表、全部排班、医生与科室
                const [resvResp, schedResp, docResp, depResp] = await Promise.all([
                    axios.get(`/reservation/select/${pId}`),
                    axios.get('/schedule/query'),
                    axios.get('/doctor/query'),
                    axios.get('/department/query')
                ]);
                
                if (resvResp.data.code === 200) {
                    // 原始预约列表
                    let reservations = resvResp.data.data || [];
                    
                    // 根据筛选状态过滤（客户端过滤），兼容 rState/rstate/state
                    const statusVal = document.getElementById('reservationStatus')?.value || '';
                    if (statusVal !== '') {
                        reservations = reservations.filter(r => {
                            const s = r?.rState ?? r?.rstate ?? r?.state;
                            return String(Number(s)) === statusVal;
                        });
                    }
                    
                    const tbody = document.getElementById('myReservationsTable');
                    tbody.innerHTML = '';
                    
                    // 建立映射
                    const schedules = (schedResp.data && schedResp.data.code === 200 ? (schedResp.data.data || []) : []);
                    const sIdMap = new Map();
                    schedules.forEach(s => { sIdMap.set(s.sId || s.sid, s); });
                    const doctorMap = new Map();
                    const doctors = (docResp.data && docResp.data.code === 200 ? (docResp.data.data || []) : []);
                    doctors.forEach(d => {
                        const id = d.dId || d.did || d.id;
                        const name = d.dName || d.dname || d.name || '医生';
                        doctorMap.set(id, name);
                    });
                    const depMap = new Map();
                    const deps = (depResp.data && depResp.data.code === 200 ? (depResp.data.data || []) : []);
                    deps.forEach(dep => depMap.set(dep.depId, dep.depName));
                    
                    reservations.forEach(reservation => {
                        // 归一化状态：仅 0/1/2 有效（0-待就诊，1-已就诊，2-已取消）
                        const rawState = Number(reservation.rState ?? reservation.rstate ?? reservation.state);
                        const nState = [0,1,2].includes(rawState) ? rawState : 0;
                        const statusText = getStatusText(nState);
                        const statusClass = getStatusClass(nState);
                        
                        // 预约时间
                        let timeStr = '-';
                        try {
                            const rTimeVal = reservation.rTime || reservation.rtime;
                            if (rTimeVal) {
                                const d = typeof rTimeVal === 'string' ? new Date(rTimeVal) : new Date(rTimeVal);
                                if (!isNaN(d)) timeStr = d.toLocaleString();
                            } else if (reservation.sId || reservation.sid) {
                                const sch = sIdMap.get(reservation.sId || reservation.sid);
                                if (sch) {
                                    const dateVal = sch.date;
                                    const ymd = typeof dateVal === 'string' ? dateVal.split('T')[0] : new Date(dateVal).toISOString().split('T')[0];
                                    timeStr = `${ymd} ${sch.time || ''}`.trim();
                                }
                            }
                        } catch (e) { /* 保持 '-' */ }
                        
                        // 医生与科室名称解析
                        const sch = sIdMap.get(reservation.sId || reservation.sid) || {};
                        const dIdFromSch = sch.dId || sch.did;
                        const depIdFromSch = sch.depId || sch.depid;
                        const doctorName = reservation.dName || reservation.dname || doctorMap.get(dIdFromSch) || '医生';
                        const depName = reservation.depName || depMap.get(depIdFromSch) || '科室';
                        
                        // 预约号
                        const rNumber = reservation.rNum || reservation.rnum || '-';
                        
                        const rIdSafe = reservation.rId || reservation.rid || reservation.RId || reservation.RID || 0;
                        const row = `
                            <tr>
                                <td>${timeStr}</td>
                                <td>${depName}</td>
                                <td>${doctorName}</td>
                                <td>${rNumber}</td>
                                <td><span class="badge ${statusClass}">${statusText}</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewReservation(${rIdSafe})">查看</button>
                                    ${nState === 0 ? `<button class=\"btn btn-sm btn-outline-danger\" onclick=\"cancelReservation(${rIdSafe})\">取消</button>` : ''}
                                </td>
                            </tr>
                        `;
                        tbody.innerHTML += row;
                    });
                    if (reservations.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">暂无预约记录</td></tr>';
                    }
                } else {
                    document.getElementById('myReservationsTable').innerHTML = 
                        '<tr><td colspan="6" class="text-center text-muted">暂无预约记录</td></tr>';
                }
            } catch (error) {
                console.error('加载预约记录失败:', error);
                document.getElementById('myReservationsTable').innerHTML = 
                    '<tr><td colspan="6" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        // 获取状态文本（与后端一致：0-待就诊，1-已就诊，2-已取消）
        function getStatusText(status) {
            const statusMap = {
                0: '待就诊',
                1: '已就诊',
                2: '已取消'
            };
            return statusMap[status] || '待就诊';
        }

        // 获取状态样式（与后端状态语义对应）
        // 0-待就诊: 黄色，1-已就诊: 绿色，2-已取消: 灰色
        function getStatusClass(status) {
            const classMap = {
                0: 'bg-warning',
                1: 'bg-success',
                2: 'bg-secondary'
            };
            return classMap[status] || 'bg-warning';
        }

        // 查看预约详情（医生信息 + 预约时段）
        async function viewReservation(rId) {
            try {
                // 兼容不同字段形态：数字/字符串/对象
                if (rId && typeof rId === 'object') {
                    rId = rId.rId || rId.rid || rId.id || rId.RId || rId.RID;
                }
                if (typeof rId === 'string') {
                    rId = rId.trim();
                    if (/^\d+$/.test(rId)) rId = parseInt(rId, 10);
                }
                if (!rId || isNaN(rId)) {
                    alert('无效的预约ID');
                    return;
                }

                // 1) 获取预约基本信息
                const resvResp = await axios.get(`/reservation/info/${rId}`);
                if (!resvResp || resvResp.data.code !== 200 || !resvResp.data.data) {
                    alert('获取预约信息失败');
                    return;
                }
                const resv = resvResp.data.data;
                const sId = resv.sId || resv.sid;
                const rNum = resv.rNum || resv.rnum || '';
                const rInfo = resv.rInfo || resv.rinfo || '';
                const rStateRaw = resv.rState ?? resv.rstate ?? resv.state;
                const rState = [0,1,2].includes(Number(rStateRaw)) ? Number(rStateRaw) : 0;
                const statusText = getStatusText(rState);

                // 2) 查询排班，找到该预约对应的时段/医生/科室
                const schedResp = await axios.get('/schedule/query');
                const schedules = (schedResp.data && schedResp.data.code === 200 ? (schedResp.data.data || []) : []);
                const schedule = schedules.find(s => (s.sId || s.sid) === sId) || {};
                const dId = schedule.dId || schedule.did;
                const depId = schedule.depId || schedule.depid;
                let dateStr = '-';
                try {
                    const raw = schedule.date;
                    if (raw) {
                        if (typeof raw === 'string') {
                            dateStr = raw.split('T')[0];
                        } else {
                            const d = new Date(raw);
                            if (!isNaN(d)) dateStr = d.toISOString().split('T')[0];
                        }
                    }
                } catch (e) { /* ignore */ }
                const timeStr = schedule.time || '-';

                // 3) 获取医生信息
                let doctorName = '医生';
                let doctorTitle = '';
                if (dId) {
                    try {
                        const docResp = await axios.get(`/doctor/info/${dId}`);
                        if (docResp.data && docResp.data.code === 200 && docResp.data.data) {
                            const d = docResp.data.data;
                            doctorName = d.dName || d.dname || doctorName;
                            doctorTitle = d.dTitle || d.dtitle || '';
                        }
                    } catch (e) { /* ignore */ }
                }

                // 4) 获取科室名称（尽力而为）
                let depName = depId ? `科室${depId}` : '科室';
                if (depId) {
                    try {
                        const depResp = await axios.get(`/department/Info/${depId}`);
                        if (depResp.data && depResp.data.code === 200 && depResp.data.data) {
                            depName = depResp.data.data.depName || depName;
                        }
                    } catch (e) { /* ignore */ }
                }

                const lines = [
                    `预约详情：`,
                    `预约号：${rNum || '-'}`,
                    `预约状态：${statusText}`,
                    '',
                    `医生：${doctorName}${doctorTitle ? '（' + doctorTitle + '）' : ''}`,
                    `科室：${depName}`,
                    `日期：${dateStr}`,
                    `时段：${timeStr}`,
                    '',
                    `预约备注：${rInfo || '无'}`
                ];
                alert(lines.join('\n'));
            } catch (error) {
                console.error('查看预约详情失败:', error);
                alert('查看预约详情失败，请稍后重试');
            }
        }

        // 取消预约
        async function cancelReservation(rId) {
            if (confirm('确定要取消这个预约吗？')) {
                try {
                    const response = await axios.delete(`/reservation/delete/${rId}`);
                    
                    if (response.data.code === 200) {
                        alert('预约已取消');
                        loadMyReservations();
                    } else {
                        alert('取消失败：' + (response.data.msg || '未知错误'));
                    }
                } catch (error) {
                    console.error('取消预约失败:', error);
                    alert('取消失败，请检查网络连接');
                }
            }
        }

        // 加载我的病历
        let myMedicalRecords = [];
        async function loadMedicalRecords() {
            try {
                const tbody = document.getElementById('medicalRecordsTable');
                if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">加载中...</td></tr>';

                // 获取当前患者ID
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                let pId = userInfo.pId || userInfo.pid || userInfo.PId || userInfo.PID || userInfo.id || userInfo.uid;
                if (!pId) {
                    try {
                        const u = await axios.get('/user/info');
                        const uData = u.data?.data || u.data || {};
                        pId = uData.pid || uData.pId || uData.PId || uData.id || uData.uId || uData.uid || null;
                    } catch (e) { /* ignore */ }
                }

                // 获取该患者的预约列表（用于通过 rId 反向过滤病历）
                let myReservations = [];
                if (pId) {
                    try {
                        const r = await axios.get(`/reservation/select/${pId}`);
                        if (r.data && r.data.code === 200) myReservations = r.data.data || [];
                    } catch (e) { /* ignore */ }
                }
                const myRIds = new Set((myReservations || []).map(x => x.rId || x.rid).filter(Boolean));

                // 拉取全部病历，前端过滤（后端未提供按患者过滤的API）
                const res = await axios.get('/medical/record/queryAll');
                if (!(res.data && res.data.code === 200)) {
                    if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">加载失败</td></tr>';
                    return;
                }
                const all = res.data.data || [];

                // 患者姓名兜底
                let myName = userInfo.uName || '';
                if (!myName && pId) {
                    try {
                        const p = await axios.get(`/patient/info/${pId}`);
                        if (p.data && p.data.code === 200) myName = p.data.data?.pName || p.data.data?.pname || '';
                    } catch (e) { /* ignore */ }
                }

                myMedicalRecords = all.filter(rec => {
                    if (!rec || typeof rec !== 'object') return false;
                    // 1) 直接按pId过滤（若后端返回了pId）
                    const pidInRec = rec.pId || rec.pid || rec.PId || rec.PID;
                    if (pId && pidInRec && String(pidInRec) === String(pId)) return true;
                    // 2) 按预约ID匹配
                    const ridInRec = rec.rId || rec.rid;
                    if (myRIds.size && ridInRec && myRIds.has(ridInRec)) return true;
                    // 3) 按姓名兜底
                    if (myName && (rec.pname === myName || rec.pName === myName)) return true;
                    return false;
                });

                // 渲染
                if (!myMedicalRecords.length) {
                    if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无病历记录</td></tr>';
                    return;
                }

                const rows = myMedicalRecords.map(rec => {
                    // 就诊时间
                    let timeStr = '-';
                    try {
                        const t = rec.mTime;
                        if (t) {
                            if (typeof t === 'string') timeStr = new Date(t).toLocaleString();
                            else {
                                const d = new Date(t);
                                if (!isNaN(d)) timeStr = d.toLocaleString();
                            }
                        }
                    } catch (e) { /* ignore */ }

                    const depName = rec.depName || '科室';
                    const docName = rec.dname || rec.dName || '医生';
                    const result = rec.mResult || '-';
                    const mid = rec.mId || 0;
                    return `
                        <tr>
                            <td>${timeStr}</td>
                            <td>${depName}</td>
                            <td>${docName}</td>
                            <td>${result}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="viewMedicalRecord(${mid})">查看</button>
                            </td>
                        </tr>
                    `;
                }).join('');
                if (tbody) tbody.innerHTML = rows;
            } catch (error) {
                console.error('加载病历记录失败:', error);
                const tbody = document.getElementById('medicalRecordsTable');
                if (tbody) tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">加载失败</td></tr>';
            }
        }
 
        // 查看病历详情
        function viewMedicalRecord(recordId) {
            try {
                if (!recordId || recordId <= 0) { alert('无效的病历ID'); return; }
                const rec = (myMedicalRecords || []).find(r => (r.mId || 0) === recordId);
                if (!rec) { alert('未找到病历详情'); return; }

                const lines = [
                    '病历详情：',
                    `病历ID：${rec.mId}`,
                    `预约ID：${rec.rId || rec.rid || '-'}`,
                    `患者：${rec.pname || '-'}`,
                    `医生：${rec.dname || rec.dName || '-'}`,
                    `科室：${rec.depName || '-'}`,
                    `就诊时间：${rec.mTime || '-'}`,
                    '',
                    '诊断结果：',
                    rec.mResult || '无',
                    '',
                    '病情描述：',
                    rec.mInfo || '无',
                    '',
                    '医嘱：',
                    rec.mAdvice || '无'
                ];
                alert(lines.join('\n'));
            } catch (e) {
                console.error('查看病历详情失败:', e);
                alert('查看病历详情失败，请稍后重试');
            }
        }

        // 加载个人信息
        async function loadProfile() {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                let pId = userInfo.pId || userInfo.pid || userInfo.PId || userInfo.PID || userInfo.id || userInfo.uid;
                
                // 兜底：从 /user/info 获取当前用户再推断 pId（User.id 绑定患者ID；某些环境可能直接返回 pid）
                if (!pId) {
                    try {
                        const u = await axios.get('/user/info');
                        // /user/info 控制器可能直接返回 User 或 {code,data}
                        const uData = u.data?.data || u.data || {};
                        pId = uData.pid || uData.pId || uData.PId || uData.id || uData.uId || uData.uid || null;
                    } catch (e) {
                        console.warn('获取 /user/info 失败:', e);
                    }
                }
                // console.debug('patient pId =', pId);
                
                if (!pId) {
                    console.warn('未找到患者ID，无法加载个人信息');
                    return;
                }
                
                const response = await axios.get(`/patient/info/${pId}`);
                
                if (response.data.code === 200) {
                    const patient = response.data.data || {};
                    // console.debug('patient info object =', patient);
                    const getField = (obj, names, def='') => {
                        for (const n of names) if (obj[n] !== undefined && obj[n] !== null) return obj[n];
                        return def;
                    };
                    const formatDate = (val) => {
                        if (!val) return '';
                        try {
                            if (typeof val === 'number' || (/^\d+$/.test(val))) {
                                const ts = typeof val === 'number' ? val : parseInt(val, 10);
                                const d = new Date(ts);
                                if (!isNaN(d)) return d.toLocaleDateString();
                            }
                            if (typeof val === 'object') {
                                const y = val.year || val.y;
                                const m = (val.monthValue || val.month || val.m);
                                const d0 = val.dayOfMonth || val.day || val.d;
                                if (y && m && d0) {
                                    const d = new Date(y, m - 1, d0);
                                    if (!isNaN(d)) return d.toLocaleDateString();
                                }
                                if (val.date) {
                                    return formatDate(val.date);
                                }
                            }
                            if (typeof val === 'string') {
                                const s = val.replace('T', ' ');
                                const d = new Date(s);
                                if (!isNaN(d)) return d.toLocaleDateString();
                                const onlyDate = s.split(' ')[0] || s;
                                return onlyDate.replace(/\//g,'-');
                            }
                            return '';
                        } catch { return ''; }
                    };
                    
                    const pidVal = getField(patient, ['pId','pid','p_id','id']);
                    const nameVal = getField(patient, ['pName','pname','p_name','name']);
                    const cardIdVal = getField(patient, ['pCardId','pcardId','pCardID','pcardid','cardId','cardID','p_card_id']);
                    const phoneVal = getField(patient, ['pPhone','pphone','phone','p_phone']);
                    const createVal = getField(patient, ['pCreateTime','pcreateTime','pcreatetime','createTime','ctime','pCreateTimeStr','create_time','p_create_time','registerTime']);
                    console.log('patient raw create time =', createVal);
                    
                    document.getElementById('profilePId').value = pidVal || '';
                    document.getElementById('profileName').value = nameVal || '';
                    document.getElementById('profileCardId').value = cardIdVal || '';
                    document.getElementById('profilePhone').value = phoneVal || '';
                    document.getElementById('profileCreateTime').value = formatDate(createVal);
                } else {
                    console.warn('获取患者信息失败:', response.data);
                }
            } catch (error) {
                console.error('加载个人信息失败:', error);
            }
        }

        // 编辑个人信息
        function editProfile() {
            alert('编辑个人信息功能待实现');
        }

        // 住院办理相关函数
        
        // 显示住院申请表单
        function showHospitalizationApplication() {
            document.getElementById('hospitalizationApplication').style.display = 'block';
            loadDepartmentsForAdmission();
        }

        // 取消住院申请
        function cancelHospitalizationApplication() {
            document.getElementById('hospitalizationApplication').style.display = 'none';
            document.getElementById('hospitalizationForm').reset();
        }

        // 加载科室列表（用于住院申请）
        async function loadDepartmentsForAdmission() {
            try {
                const response = await axios.get('/department/query');
                if (response.data.code === 200) {
                    const departments = response.data.data;
                    const select = document.getElementById('admissionDepartment');
                    select.innerHTML = '<option value="">请选择科室</option>';
                    
                    departments.forEach(dept => {
                        const option = document.createElement('option');
                        option.value = dept.depId;
                        option.textContent = dept.depName;
                        select.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载科室列表失败:', error);
            }
        }

        // 科室选择变化时加载医生
        document.addEventListener('DOMContentLoaded', function() {
            const depSelect = document.getElementById('admissionDepartment');
            if (depSelect) {
                depSelect.addEventListener('change', function() {
                    loadDoctorsForAdmission(this.value);
                });
            }
        });

        // 加载医生列表（用于住院申请）
        async function loadDoctorsForAdmission(depId) {
            try {
                if (!depId) {
                    document.getElementById('admissionDoctor').innerHTML = '<option value="">请选择医生（可选）</option>';
                    return;
                }

                const response = await axios.get(`/doctor/query/${depId}`);
                const doctors = response.data.code === 200 ? response.data.data : [];
                
                const select = document.getElementById('admissionDoctor');
                select.innerHTML = '<option value="">请选择医生（可选）</option>';
                
                doctors.forEach(doctor => {
                    const option = document.createElement('option');
                    option.value = doctor.dId || doctor.did;
                    option.textContent = `${doctor.dName || doctor.dname} (${doctor.dTitle || doctor.dtitle || ''})`;
                    select.appendChild(option);
                });
            } catch (error) {
                console.error('加载医生列表失败:', error);
            }
        }

        // 提交住院申请
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('hospitalizationForm');
            if (form) {
                form.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    
                    try {
                        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                        const pId = userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid;
                        
                        if (!pId) {
                            alert('未找到患者ID，无法提交申请');
                            return;
                        }

                        // 校验并归一化表单字段
                        const depEl = document.getElementById('admissionDepartment');
                        const docEl = document.getElementById('admissionDoctor');
                        const reasonEl = document.getElementById('admissionReason');
                        const diagEl = document.getElementById('preliminaryDiagnosis');
                        const remarkEl = document.getElementById('admissionRemark');
                        const urgencyEl = document.getElementById('urgencyLevel');
                        const wardEl = document.getElementById('wardType');

                        const depIdVal = (depEl && depEl.value) ? parseInt(depEl.value, 10) : NaN;
                        if (!depIdVal || Number.isNaN(depIdVal)) {
                            alert('请选择申请科室');
                            return;
                        }

                        const dIdVal = (docEl && docEl.value) ? parseInt(docEl.value, 10) : null; // 可为空
                        const reasonVal = (reasonEl && reasonEl.value ? reasonEl.value.trim() : '');
                        if (!reasonVal) {
                            alert('请填写住院原因');
                            return;
                        }

                        const pIdNum = Number(pId);
                        const formData = {
                            // 实体字段（后端识别）
                            pId: pIdNum,
                            depId: depIdVal,
                            dId: dIdVal,
                            aReason: reasonVal,
                            aDiagnosis: (diagEl && diagEl.value ? diagEl.value.trim() : ''),
                            aUrgency: (urgencyEl && urgencyEl.value ? parseInt(urgencyEl.value, 10) : 1),
                            wType: (wardEl && wardEl.value ? wardEl.value : ''),
                            aRemark: (remarkEl && remarkEl.value ? remarkEl.value.trim() : ''),
                            // 兼容别名（部分后端实现/拦截器可能读取这些别名）
                            pid: pIdNum,
                            did: dIdVal,
                            depid: depIdVal,
                            areason: reasonVal,
                            adiagnosis: (diagEl && diagEl.value ? diagEl.value.trim() : ''),
                            aurgency: (urgencyEl && urgencyEl.value ? parseInt(urgencyEl.value, 10) : 1),
                            wtype: (wardEl && wardEl.value ? wardEl.value : ''),
                            aremark: (remarkEl && remarkEl.value ? remarkEl.value.trim() : '')
                        };

                        console.log('提交住院申请数据 formData =', JSON.stringify(formData));

                        const response = await axios.post('/admission/apply', formData);
                        
                        if (response.data.code === 200) {
                            alert('住院申请提交成功！');
                            cancelHospitalizationApplication();
                            loadHospitalizationApplications();
                        } else {
                            console.error('住院申请失败 formData =', formData, 'resp =', response.data);
                            alert('申请失败：' + (response.data.msg || '未知错误'));
                        }
                    } catch (error) {
                        console.error('提交住院申请失败 formData error =', error);
                        alert('提交失败，请检查网络连接');
                    }
                });
            }
        });

        // 加载我的住院申请记录
        async function loadHospitalizationApplications() {
            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                const pId = userInfo.pId || userInfo.id || userInfo.uid || userInfo.pid;
                
                if (!pId) {
                    document.getElementById('hospitalizationApplicationsTable').innerHTML = 
                        '<tr><td colspan="7" class="text-center text-muted">无法加载：缺少患者ID</td></tr>';
                    return;
                }

                const response = await axios.get(`/admission/patient/${pId}`);
                
                if (response.data.code === 200) {
                    const applications = response.data.data || [];
                    const tbody = document.getElementById('hospitalizationApplicationsTable');
                    tbody.innerHTML = '';
                    
                    if (applications.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="7" class="text-center text-muted">暂无住院申请记录</td></tr>';
                        return;
                    }

                    // 获取科室信息用于显示
                    const depResponse = await axios.get('/department/query');
                    const departments = depResponse.data.code === 200 ? depResponse.data.data : [];
                    const depMap = new Map();
                    departments.forEach(dep => depMap.set(dep.depId, dep.depName));

                    applications.forEach(app => {
                        // 兼容不同字段命名
                        const get = (obj, keys, defVal = undefined) => {
                            for (const k of keys) {
                                if (obj[k] !== undefined && obj[k] !== null) return obj[k];
                            }
                            return defVal;
                        };
                        const aId = get(app, ['aId','aid','AId']);
                        const aNumber = get(app, ['aNumber','anumber','ANumber','a_number'], '-');
                        const depIdVal = get(app, ['depId','depid','dep_id']);
                        const wTypeVal = get(app, ['wType','wtype','w_type'], '-');
                        const aUrgencyVal = Number(get(app, ['aUrgency','aurgency','a_urgency'], 1));
                        const aStateValRaw = get(app, ['aState','astate','a_state'], 0);
                        const aStateVal = [0,1,2,3,4].includes(Number(aStateValRaw)) ? Number(aStateValRaw) : 0;
                        const applyRaw = get(app, ['aApplyTime','aapplyTime','a_apply_time','applyTime']);

                        // 状态/紧急程度显示
                        const statusText = getAdmissionStatusText(aStateVal);
                        const statusClass = getAdmissionStatusClass(aStateVal);
                        const urgencyText = getUrgencyText(aUrgencyVal);

                        // 科室名称解析
                        let depName = depMap.get(depIdVal) || get(app, ['depName','depname']) || '未知科室';

                        // 时间解析
                        let applyTime = '-';
                        try {
                            if (applyRaw) {
                                if (typeof applyRaw === 'string') {
                                    const d = new Date(applyRaw);
                                    if (!isNaN(d)) applyTime = d.toLocaleString();
                                    else applyTime = applyRaw.replace('T',' ').split('.')[0];
                                } else {
                                    const d = new Date(applyRaw);
                                    if (!isNaN(d)) applyTime = d.toLocaleString();
                                }
                            }
                        } catch (e) { /* ignore */ }

                        const row = `
                            <tr>
                                <td>${aNumber}</td>
                                <td>${applyTime}</td>
                                <td>${depName}</td>
                                <td>${wTypeVal || '-'}</td>
                                <td>${urgencyText}</td>
                                <td><span class="badge ${statusClass}">${statusText}</span></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewAdmissionApplication(${aId})">查看</button>
                                    ${aStateVal === 0 ? `<button class=\"btn btn-sm btn-outline-danger\" onclick=\"cancelAdmissionApplication(${aId})\">取消</button>` : ''}
                                </td>
                            </tr>
                        `;
                        tbody.innerHTML += row;
                    });
                } else {
                    document.getElementById('hospitalizationApplicationsTable').innerHTML = 
                        '<tr><td colspan="7" class="text-center text-muted">加载失败</td></tr>';
                }
            } catch (error) {
                console.error('加载住院申请记录失败:', error);
                document.getElementById('hospitalizationApplicationsTable').innerHTML = 
                    '<tr><td colspan="7" class="text-center text-muted">加载失败</td></tr>';
            }
        }

        // 获取申请状态文本
        function getAdmissionStatusText(status) {
            const statusMap = {
                0: '待审批',
                1: '已批准',
                2: '已拒绝',
                3: '已入院',
                4: '已取消'
            };
            return statusMap[status] || '未知状态';
        }

        // 获取申请状态样式
        function getAdmissionStatusClass(status) {
            const classMap = {
                0: 'bg-warning',
                1: 'bg-success',
                2: 'bg-danger',
                3: 'bg-info',
                4: 'bg-secondary'
            };
            return classMap[status] || 'bg-secondary';
        }

        // 获取紧急程度文本
        function getUrgencyText(urgency) {
            const urgencyMap = {
                1: '普通',
                2: '紧急',
                3: '危重'
            };
            return urgencyMap[urgency] || '普通';
        }

        // 查看住院申请详情
        async function viewAdmissionApplication(aId) {
            try {
                const response = await axios.get(`/admission/info/${aId}`);
                
                if (response.data.code === 200) {
                    const app = response.data.data;
                    
                    // 获取科室和医生信息
                    let depName = '未知科室';
                    let doctorName = '未指定医生';
                    
                    try {
                        const depResponse = await axios.get('/department/query');
                        if (depResponse.data.code === 200) {
                            const dept = depResponse.data.data.find(d => d.depId === app.depId);
                            if (dept) depName = dept.depName;
                        }
                        
                        if (app.dId) {
                            const docResponse = await axios.get(`/doctor/info/${app.dId}`);
                            if (docResponse.data.code === 200) {
                                const doctor = docResponse.data.data;
                                doctorName = `${doctor.dName || doctor.dname} (${doctor.dTitle || doctor.dtitle || ''})`;
                            }
                        }
                    } catch (e) { /* ignore */ }

                    const lines = [
                        '住院申请详情：',
                        `申请编号：${app.aNumber || '-'}`,
                        `申请状态：${getAdmissionStatusText(app.aState)}`,
                        `申请时间：${app.aApplyTime ? new Date(app.aApplyTime).toLocaleString() : '-'}`,
                        '',
                        `申请科室：${depName}`,
                        `申请医生：${doctorName}`,
                        `病房类型：${app.wType || '-'}`,
                        `紧急程度：${getUrgencyText(app.aUrgency)}`,
                        '',
                        `住院原因：${app.aReason || '-'}`,
                        `初步诊断：${app.aDiagnosis || '-'}`,
                        `备注信息：${app.aRemark || '-'}`,
                        ''
                    ];

                    if (app.aState === 2 && app.aRejectReason) {
                        lines.push(`拒绝原因：${app.aRejectReason}`);
                    }

                    if (app.aApproveTime) {
                        lines.push(`审批时间：${new Date(app.aApproveTime).toLocaleString()}`);
                    }

                    alert(lines.join('\n'));
                } else {
                    alert('获取申请详情失败');
                }
            } catch (error) {
                console.error('查看申请详情失败:', error);
                alert('查看申请详情失败，请稍后重试');
            }
        }

        // 取消住院申请
        async function cancelAdmissionApplication(aId) {
            if (confirm('确定要取消这个住院申请吗？')) {
                try {
                    // 由于没有专门的取消接口，我们更新申请状态为已取消
                    const response = await axios.get(`/admission/info/${aId}`);
                    if (response.data.code === 200) {
                        const app = response.data.data;
                        app.aState = 4; // 已取消
                        
                        // 这里需要后端提供更新接口，暂时提示用户联系管理员
                        alert('取消申请功能需要联系管理员处理');
                        // TODO: 实现取消申请的后端接口
                    }
                } catch (error) {
                    console.error('取消申请失败:', error);
                    alert('取消申请失败，请稍后重试');
                }
            }
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                window.location.href = '/login';
            }
        }
    </script>

    <style>
        .step-item {
            position: relative;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: bold;
            transition: all 0.3s;
        }
        .step-number.active {
            background: #007bff;
            color: white;
        }
        .step-text {
            font-size: 14px;
            color: #6c757d;
        }
    </style>
</body>
</html>
